/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package com.moon.admin.sys.controller;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.moon.admin.framework.domain.Kv;
import com.moon.admin.framework.domain.MoonPage;
import com.moon.admin.framework.mybatisplus.query.Condition;
import com.moon.admin.framework.secure.annotation.FormRepeat;
import com.moon.admin.framework.secure.annotation.PreAuth;
import com.moon.admin.framework.springmvc.domain.R;
import com.moon.admin.framework.syslog.annotation.SysLog;
import com.moon.admin.framework.util.ToolUtils;
import com.moon.admin.sys.domain.query.ModuleQuery;
import com.moon.admin.sys.entity.SysMenuEntity;
import com.moon.admin.sys.entity.SysModuleEntity;
import com.moon.admin.sys.service.SysMenuService;
import com.moon.admin.sys.service.SysModuleService;

import io.swagger.annotations.Api;

/**
 * 系统模块
 * @author ninglong
 */
@RestController
@RequestMapping("/module")
@Api(value="系统模块",tags="系统模块")
public class SysModuleController {

	@Autowired
	private SysModuleService moduleService;
	@Autowired
	private SysMenuService menuService;
	
	@PostMapping("/list")
	public R<MoonPage<SysModuleEntity>> list(@RequestBody ModuleQuery query){
		LambdaQueryWrapper<SysModuleEntity> ew = Condition.getQueryWrapper(new SysModuleEntity(), query);
		IPage<SysModuleEntity> page = moduleService.page(Condition.getPage(query),ew);
		return R.success(MoonPage.of(page));
	}
	
	@SysLog(fun="系统模块",mod="保存系统模块")
	@PreAuth({"sys_platform_add","sys_platform_edit"})
	@PostMapping("/save")
	@FormRepeat
	public R<Void> save(@RequestBody SysModuleEntity moduleEntity){
		moduleService.saveOrUpdate(moduleEntity);
		return R.success();
	}
	
	@GetMapping(value = "removeById")
	@PreAuth("sys_platform_remove")
	@SysLog(fun="系统模块管理",mod="删除系统模块")
	@FormRepeat
	public R<Void> removeById(Integer id) {
		if(ToolUtils.isNull(id)) {
			return R.fail("请选择要删除的系统模块");
		}
		//需要判断是否有菜单
		int count = menuService.count(Wrappers.<SysMenuEntity>lambdaQuery().eq(SysMenuEntity::getModuleId, id));
		if(count>0) {
			return R.fail("该模块下还有系统菜单，不能删除");
		}
		return R.status(moduleService.removeById(id));
	}
	
	@GetMapping("/getList")
	public R<List<Kv>> getList(){
		List<Kv> list = moduleService.list().stream().map(entity->Kv.builder().label(entity.getModuleName()).value(String.valueOf(entity.getId())).build()).collect(Collectors.toList());
		return R.success(list);
	}
}